import modules from "./modules";
//这里仅示范npm安装方式的引入，其它方式引入请看最上面【安装】部分
import { RouterMount, createRouter } from "uni-simple-router";
import { getToken } from "@/utils/auth";
import { themeColor } from "@/const/theme/color";
import store from "@/store";

//初始化
const router = createRouter({
  platform: process.env.VUE_APP_PLATFORM,
  routes: [...modules], //路由表
});

const whiteList = [
  "/pages/home/index",
  "/pages/sp-common/pages/login/index",
  "/pages/sp-common/pages/agreement/index",
  "/pages/sp-common/pages/h5-login/index",
];
const resetLoginInfo = (to) => {
  if (to.path === "/pages/sp-common/pages/login/index") {
    store.dispatch("sp-common/auth/clearTokenAction");
    store.dispatch("sp-common/auth/clearUserInfoAction");
    store.dispatch("sp-common/auth/clearPubUserInfoAction");
  }
};

//全局路由前置守卫
router.beforeEach((to, from, next) => {
  const isToken = !!getToken();
  if (!isToken) {
    if (whiteList.includes(to.path)) {
      next();
    } else {
      uni.showModal({
        title: "提示",
        content: "暂无登录，请登录",
        confirmColor: themeColor.primary,
        success: (res) => {
          if (res.confirm) {
            next({
              path: "/pages/sp-common/pages/login/index",
              NAVTYPE: "push",
            });
          } else {
            next(false);
          }
        },
      });
    }
  } else {
    next();
  }
  resetLoginInfo(to);
});
// 全局路由后置守卫
router.afterEach((to, from) => {
  // console.log("全局路由后置守卫");
});

export { router, RouterMount };
